
import { MessageBox } from "element-ui";
import store from "../store/index";

let lastTime = new Date().getTime();
let currentTime = new Date().getTime();
let timeOut = store.state.timeOut; // 设置超时时间
let is_open_message = false;
let is_out = false;

window.onload = () => {
  if (window.localStorage.getItem("is_out")) {
    is_out = window.localStorage.getItem("is_out")
    if (is_out && JSON.parse(is_out)) {
      tip();
    }
  } else {
    window.localStorage.setItem("is_out", is_out);
  }
  window.document.onmousedown = () => {
    window.localStorage.setItem("lastTime", new Date().getTime())
  }
}

const checkTimeOut = () => {
  let storage = window.localStorage.getItem("user");
  if (!storage) {
    return
  }
  if (is_open_message) {
    return
  }

  // 更新当前时间
  currentTime = new Date().getTime();
  lastTime = window.localStorage.getItem("lastTime");
  // 判断是否超时
  if (currentTime - lastTime > timeOut) {
    is_open_message = true;
    is_out = true;
    window.localStorage.setItem("is_out", is_out)
    tip();
  }
}

const tip = () => {
  MessageBox.confirm('登录信息已过期,请重新登录', '提示', {
    confirmButtonText: "确定",
    showCancelButton: false,
    showClose: false,
    type: 'warning'
  }).then(() => {
    is_open_message = false;
    is_out = false;
    window.localStorage.clear();
    window.location.href = '/';
  }).catch(() => {

  })
}

export default function () {
  window.setInterval(checkTimeOut, store.state.domTimeVal)
}